package com.shujia.flink.window;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @author shujia
 */
public class Demo5ProcessingTimeSessionWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> lines = env.socketTextStream("master", 8888);

        DataStream<Tuple2<String, Integer>> kv = lines.map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        KeyedStream<Tuple2<String, Integer>, String> keyBy = kv.keyBy(k -> k.f0);

        /*
         * 会话窗口,一段时间没有数据生成一个窗口
         * EventTimeSessionWindows:事件时间的会话窗口
         * ProcessingTimeSessionWindows:处理时间的会话窗口
         */

        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windows = keyBy
                //如果5秒没有数据计算一次
                .window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)));

        windows.sum(1)
                .print();


        env.execute();

    }
}
